﻿using KeepAccounts.Common.Config;
using KeepAccounts.Common.HttpContextUser;
using KeepAccounts.Models;
using KeepAccounts.Models.Enums.Book;
using KeepAccounts.Models.Models;
using KeepAccounts.Models.Models.Book;
using KeepAccounts.Models.Models.PageModel;
using KeepAccounts.Models.PageModel;
using KeepAccounts.Models.ViewModels.Book;
using KeepAccounts.Repository.BookClass;
using KeepAccounts.Repository.UnitOfWork;
using KeepAccounts.Services.BaseServices;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KeepAccounts.Repository.Book
{
    public class BookServices : BaseServices<BookEntity>, IBookServices
    {
        private readonly IBookRepository _bookRepository;
        private readonly IBookClassRepository _bookClassRepository;
        private readonly IAspNetUser _aspNetUser;

        public BookServices(IBookRepository dal, IBookClassRepository bookClassRepository, IAspNetUser aspNetUser)
        {
            base.BaseDal = dal;
            _bookRepository = dal;
            _bookClassRepository = bookClassRepository;
            _aspNetUser = aspNetUser;

        }

        public Task<bool> Delete(GuidQueryModel query)
        {
            return _bookRepository.DeleteById(query.Id);
        }

        public Task<PageResultModel<BookEntity>> FindList(BookListQueryModel query)
        {
            //query.WhereLambda = Expressionable.Create<BookEntity>().
            //      //And(s => !s.IsDeleted).
            //      AndIF(!string.IsNullOrWhiteSpace(query.Name), s => s.ClassName.Contains(query.Name) || s.Remark.Contains(query.Name)).

            //      ToExpression();

            throw new ApiException("功能未实现");
            // return _bookRepository.Pages<BookEntity>(query);
        }

        public async Task<IndexBookListViewModel> GetBookList(BookListQueryModel query)
        {

            if (!_aspNetUser.IsAuthenticated())
            {
                return new IndexBookListViewModel()
                {
                    DayBookList = new List<DayBook>(),
                };
            }
            query.YearMonth = query.YearMonth.Replace("年", "-").Replace("月", "-") + "1";
            var startTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);//默认查询当月
            if (Common.Utilities.ValidateHelper.IsDate(query.YearMonth))
            {
                startTime = Convert.ToDateTime(query.YearMonth);
            }
            var endTime = startTime.AddMonths(1).AddMinutes(-1);

            //query. = 
            var whereLambda = Expressionable.Create<BookEntity>().
                //   //And(s => !s.IsDeleted).
                AndIF(!string.IsNullOrWhiteSpace(query.Name), s => s.ClassName.Contains(query.Name) || s.Remark.Contains(query.Name)).
              And(s => s.ConsumptionTime >= startTime && s.ConsumptionTime <= endTime).
              And(s => s.UserId == _aspNetUser.UserId).
                 ToExpression();

            var bookList = await _bookRepository.Query(whereLambda, s => new BookListViewModel
            {
                AmountOfMoney = s.AmountOfMoney,
                BillType = s.BillType,
                ClassName = s.ClassName,
                ClassBg = s.ClassBg,
                ClassIcon = s.ClassIcon,
                ConsumptionTime = s.ConsumptionTime,
                Id = s.ID,
                Remark = s.Remark,
            }, " ConsumptionTime desc ,CreateTime desc ");
            //_bookRepository.QuerySelect<BookListViewModel>(qu);

            IndexBookListViewModel resModel = new IndexBookListViewModel()
            {
                TotalIncome = bookList.Where(s => s.BillType == BillTypeEnum.收入).Sum(s => s.AmountOfMoney),
                TotalExpend = bookList.Where(s => s.BillType == BillTypeEnum.支出).Sum(s => s.AmountOfMoney),
                DayBookList = new List<DayBook>(),
                YearMonth = startTime.ToString("yyyy年MM月"),
            };

            ///月末循环到月未
            while (startTime < endTime)
            {
                var dayBook = bookList.Where(s => s.ConsumptionTime >= new DateTime(endTime.Year, endTime.Month, endTime.Day) && s.ConsumptionTime <= endTime).ToList();
                if (dayBook.Count > 0)
                {
                    resModel.DayBookList.Add(new DayBook { BookList = dayBook, Day = endTime.ToLongDateString() });
                }
                endTime = endTime.AddDays(-1);
            }

            return resModel;
        }



        /// <summary>
        /// 保存修改信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Save(BookEntity model)
        {
            CheckModel(model);

            if (model.ID == Guid.Empty)
            { //保存
                model.ID = Guid.NewGuid();
                model.UserId = _aspNetUser.UserId;

                model.CreateUserID = _aspNetUser.UserId;
                return _bookRepository.Add(model).Result > 0;
            }
            else
            { //修改 


                model.UpdateUserID = _aspNetUser.UserId;
                model.UpdateTime = DateTime.Now;
                return _bookRepository.Update(model).Result;
            }
        }

        /// <summary>
        /// 保存修改信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Save(BookSaveQueryModel model)
        {

            BookEntity entity = GetBookEntity(model);
            if (entity.ID == Guid.Empty)
            { //保存
                entity.ID = Guid.NewGuid();
                entity.UserId = _aspNetUser.UserId;

                entity.CreateUserID = _aspNetUser.UserId;
                return _bookRepository.Add(entity).Result > 0;
            }
            else
            { //修改  
                entity.UpdateUserID = _aspNetUser.UserId;
                entity.UpdateTime = DateTime.Now;
                return _bookRepository.Update(entity).Result;
            }

        }

        /// <summary>
        /// 用户删除记账 
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public Task<bool> DeleteBook(GuidQueryModel query)
        {

            return _bookRepository.Update(s => new BookEntity { IsDeleted = true }, s => s.ID == query.Id && s.UserId == _aspNetUser.UserId);

        }



        private BookEntity GetBookEntity(BookSaveQueryModel model)
        {
            if (model == null)
                throw new ApiException("保存信息有误");
            var bookClass = _bookClassRepository.QueryById(model.ClassId).Result;
            if (bookClass == null)
                throw new ApiException("分类信息有误");

            if (!Enum.IsDefined(typeof(BillTypeEnum), model.BillType))
                throw new ApiException("支收类型有误");

            if (model.AmountOfMoney <= 0) throw new ApiException("金额有误");


            return new BookEntity()
            {
                AmountOfMoney = model.AmountOfMoney,
                BillType = model.BillType,
                ConsumptionTime = model.ConsumptionTime,
                ClassBg = bookClass.BgColor,
                ClassIcon = bookClass.IconName,
                ClassId = bookClass.ID,
                ClassName = bookClass.Name,
                Remark = model.Remark,
                ID = Guid.Empty,
            };
        }

        private void CheckModel(BookEntity model)
        {
            if (model == null)
                throw new ApiException("保存信息有误");
            if (string.IsNullOrWhiteSpace(model.ClassName))
                throw new ApiException("分类名称不能为空");



        }

    }
}
